package com.dd.demo01.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.sql.Connection;

/**
 * @author: lkd
 * @date: 2023/05/17/23:15
 * @Description:
 */
@Component
@Aspect
@Order(Integer.MAX_VALUE)
public class SimpleTransactionalAspect {

	@Pointcut("@annotation(com.dd.demo01.aop.annotation.SimpleTransactional)")
	public void point() {
	}

	// 简单模拟线程上下文存放connection
	public static final ThreadLocal<Connection> resources = new ThreadLocal<>();

	@Around("point()")
	public Object simpleTransactionControl(ProceedingJoinPoint pjp) throws Throwable {
		// 从 resources 获取连接
		Connection connection = resources.get();
		// 取消自动提交
		connection.setAutoCommit(false);
		Object result;
		try {
			// 执行目标方法
			result = pjp.proceed();
		} catch (Throwable e) {
			// 回滚
			connection.rollback();
			// 关闭连接
			connection.close();
			throw e;
		} finally {
			// 清理线程上下文
			resources.remove();
		}
		// 执行成功，提交
		connection.commit();
		// 关闭连接
		connection.close();
		return result;
	}

}
